package com.kaochong.xcx.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kaochong.common.util.KaoChongStringUtils;
import com.kaochong.xcx.cache.TokenCache;
import com.kaochong.xcx.cache.WechatAccessTokenCache;
import com.kaochong.xcx.entity.User;
import com.kaochong.xcx.enums.ResultEnum;
import com.kaochong.xcx.exception.KaoChongException;
import com.kaochong.xcx.pojo.model.WxAuthModel;
import com.kaochong.xcx.properties.WechatAccountProperties;
import com.kaochong.xcx.service.DemoServiceImpl;
import com.kaochong.xcx.service.UserService;
import com.kaochong.xcx.service.impl.WechatServiceImpl;
import com.kaochong.xcx.utils.AESUtil;
import com.kaochong.xcx.utils.response.ResponseUtils;
import com.kaochong.xcx.utils.response.ResultVO;
import com.kaochong.xcx.web.aspect.CurrentUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author han
 * @date 2018-05-01 12:11
 */
@RestController
@RequestMapping("/recite/wechat")
@Slf4j
public class WxOauthController {

	@Autowired
	TokenCache tokenCache;

	@Autowired
	UserService userService;

	@Autowired
	WechatAccessTokenCache wechatAccessTokenCache;

	@Autowired
	WechatServiceImpl wechatService;

	@GetMapping("/getAccessToken")
	public ResultVO getAccessToken(@RequestParam(value = "token", required = false) String token) {
		String accessToken = wechatService.getAccessToken(token);
		return ResponseUtils.success(accessToken);
	}

	/**
	 * 用code换取用户的openId
	 * @param code 前端登录获取的code
	 * @param map
	 * @return 用户微信openId
	 */
	@GetMapping("/getOpenId")
	public ResultVO auth(@RequestParam("code") String code, Map<String, Object> map) {
		log.info("【微信授权】code={}", code);
		WxAuthModel wxAuthModel = wxAuth(code);
		String openId = wxAuthModel.getOpenId();
		String sessionKey = wxAuthModel.getSessionKey();
		map.put("openId", openId);
		return ResponseUtils.success(map);
	}

	/**
	 * 用户登录
	 * @param openId 微信openId
	 * @param nickname 昵称
	 * @param portrait 头像
	 * @param fromWhere 用户来源
	 * @param map
	 * @return token 昵称
	 */
	@PostMapping("/login")
	public ResultVO login(@RequestParam("openId") String openId,
	                      @RequestParam("nickname") String nickname,
	                      @RequestParam("portrait") String portrait,
	                      @RequestParam(name = "fromwhere" , required = false ) String fromWhere,
	                      Map<String, Object> map) {
		// 1、登录获取用户信息
		Map<String, Object> loginMap = userService.login(openId, nickname, portrait ,fromWhere);
		CurrentUser currentUser = (CurrentUser) loginMap.get("currentUser");

		boolean isNewUser = (boolean) loginMap.get("isNewUser");
		String content = currentUser.getId() + "," + currentUser.getOpenId();
		String token = AESUtil.encrypt(content, AESUtil.password);
		// 2、登录信息写入redis
		currentUser.setToken(token);
		tokenCache.setToken(token, currentUser);
		map.put("token", token);
		map.put("nickname", nickname);
		map.put("portrait", portrait);
		map.put("isNewUser", isNewUser);
		return ResponseUtils.success(map);
	}

	/**
	 * 微信授权前端code换取微信openId
	 * @param code
	 * @return
	 */
	private WxAuthModel wxAuth(String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
		url = String.format(url, WechatAccountProperties.mpAppId, WechatAccountProperties.mpAppSecret, code);
		RestTemplate restTemplate = new RestTemplate();
		String response = restTemplate.getForObject(url, String.class);
		log.info("response={}", response);

		WxAuthModel object = JSONObject.parseObject(response).toJavaObject(WxAuthModel.class);
		if (null != object.getErrCode()) {
			log.error("【微信授权】response={}", object);
			throw new KaoChongException(ResultEnum.WEIXIN_JS_CODE_OAUTH_ERROR);
		}
		return object;
	}

	public static void main(String[] args) {
		String str = "{\"session_key\":\"ccvxzV2n0g+u31gLr8qqDg==\",\"expires_in\":7200," +
				"\"openid\":\"ozOH00Ia0BesxcvJkfS81uKjeIJ4\"}";
		// 方法一
		JSONObject o = JSON.parseObject(str);
		String s = o.getString("openid");
		System.out.println(s);

		// 方法二
		WxAuthModel object = JSONObject.parseObject(str).toJavaObject(WxAuthModel.class);
		System.out.println(object);
	}
	
	@Autowired
	DemoServiceImpl demoService;
	
	@GetMapping("/select")
	public ResultVO select(@RequestParam("id") Long id){
		User user = demoService.selectById(id);
		return ResponseUtils.success(user);
	}
	
	@GetMapping("/add")
	public ResultVO add(){
		User user = new User();
		user.setNickname("huohan");
		user.setPortrait("http://www.baidu.com");
		user.setTargetMarkId(KaoChongStringUtils.generateUUID());
		user.setFromWhere("test");
		user.setOpenId(KaoChongStringUtils.generateOrderNo());
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		user = demoService.insert(user);
		return ResponseUtils.success(user);
	}
}
